package com.arsl.server;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.sql.Types;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.arsl.client.util.PropertyManager;
import com.arsl.server.db.DBConnector;
import com.google.gson.Gson;

public class HttpServices extends HttpServlet {

	private static final String DOWNLOAD_PAGES_FOLDER = "/dw_pages";

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String service = request.getParameter("service");
		if ("getQRCode".equalsIgnoreCase(service)) {
			getQRCode(Integer.parseInt(request.getParameter("arPageId")),
					request, response);
			return;
		}
		if ("getPageJson".equalsIgnoreCase(service)) {
			getPageJson(Integer.parseInt(request.getParameter("arPageId")),
					request, response);
			return;
		}
	}

	private void getPageJson(int arPageId, HttpServletRequest request,
			HttpServletResponse response) {
		PaperaziServiceImpl impl = new PaperaziServiceImpl();
		impl.incHits(arPageId);
		Gson gson = new Gson();

		PrintWriter writer;
		try {
			writer = response.getWriter();
			writer.write(new Gson().toJson(impl.viewPage(arPageId, "na")));
			writer.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			List<FileItem> items = new ServletFileUpload(
					new DiskFileItemFactory()).parseRequest(request);
			String arPageId = (String) request.getParameter("hdnARPageId");
			Enumeration e = request.getParameterNames();
			while (e.hasMoreElements()) {
				System.out.println("Attrib " + (String) e.nextElement());
			}

			String imageUrl = PropertyManager.getInstance().getHostUrl()
					+ DOWNLOAD_PAGES_FOLDER + "/" + arPageId + ".jpg";

			DBConnector.runSP("set_arpage_image",
					new Object[] { Integer.parseInt(arPageId), imageUrl },
					new int[] { Types.INTEGER, Types.VARCHAR });
			for (FileItem item : items) {
				if (!item.isFormField()) {
					InputStream filecontent = item.getInputStream();
					File file = new File(new File(Thread.currentThread()
							.getContextClassLoader().getResource("").toURI()),
							"../../" + DOWNLOAD_PAGES_FOLDER + "/" + arPageId
									+ ".jpg");
					System.out.println("Save to: " + file.getAbsolutePath());
					OutputStream os = new FileOutputStream(file);
					byte[] buffer = new byte[4096];
					int bytesRead;
					while ((bytesRead = filecontent.read(buffer)) != -1) {
						os.write(buffer, 0, bytesRead);
					}
					filecontent.close();
					os.close();
				}
			}
			PrintWriter writer = response.getWriter();
			writer.write(new Gson().toJson(imageUrl));
			writer.flush();
			writer.close();
		} catch (FileUploadException e) {
			throw new ServletException("Cannot parse multipart request.", e);
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void getQRCode(int arPageId, HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		/*
		 * Object[] returns = DBConnector.runSP("get_uuid", new Object[] {
		 * arPageId }, new int[] { Types.INTEGER }, new int[] { Types.VARCHAR
		 * });
		 * 
		 * String uuid = (String) returns[0];
		 */
		String urlToEncode = PropertyManager.getInstance().getHostUrl()
				+ "/ViewPage.html?auth=na&arPageId=" + arPageId;
		ByteArrayOutputStream out = QRCode.from(urlToEncode).to(ImageType.GIF)
				.stream();

		/*
		 * FileOutputStream fout; File file = null; try {
		 * 
		 * file = new File(QR_CODE_LOCATION + uuid + ".gif"); fout = new
		 * FileOutputStream(file); fout.write(out.toByteArray());
		 * 
		 * fout.flush(); fout.close();
		 * 
		 * } catch (FileNotFoundException e) { // TODO Auto-generated catch
		 * block e.printStackTrace(); } catch (IOException e) { // TODO
		 * Auto-generated catch block e.printStackTrace(); }
		 */

		response.setContentType("image/gif");
		response.setContentLength(out.size());

		OutputStream outStream = response.getOutputStream();

		outStream.write(out.toByteArray());

		outStream.flush();
		outStream.close();

	}

}
